# coding:utf-8
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.orm import relationship

from database import dbconnect, session_maker, model_list, model_dict

_, _, DBase = dbconnect()


class JenkinsKubeInfo(DBase):
    __tablename__ = 'jenkins_kube_info'
    __table_args__ = {'extend_existing': True}
    id = Column(Integer, primary_key=True)
    name = Column(String(255), unique=True)  # 等同于代码中的cluster_code，用于区分在gitlab中生成文件时的子目录
    cluster_name = Column(String(255))  # 集群中文名，用于前端展示选择
    kube_id = Column(String(255))
    area_id = Column(Integer, ForeignKey('area.id')) # 外键关联
    area = relationship("Area")  # 关联对象

    comment = Column(String(255))

    # 查询所有
    def find_all(self):
        with session_maker() as session:
            result = session.query(JenkinsKubeInfo).all()
            list = model_list(result)
            return list

    # 根据id查询
    def find_by_id(self, id):
        with session_maker() as session:
            row = session.query(JenkinsKubeInfo).filter_by(id=id).first()
            return model_dict(row)

    # 根据id查询
    def find_by_kube_id(self, kube_id):
        with session_maker() as session:
            row = session.query(JenkinsKubeInfo).filter_by(kube_id=kube_id).first()
            return model_dict(row)

    # 查询所有
    def find_by_area(self, area_id):
        with session_maker() as session:
            result = session.query(JenkinsKubeInfo).filter_by(area_id=area_id).all()
            list = model_list(result)
            return list
